package v1

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	asr "xmediaEmu/pkg/asr/worker"
	"xmediaEmu/pkg/emulator/config"
	emu "xmediaEmu/pkg/emulator/worker"
	"xmediaEmu/pkg/log"

	. "xmediaEmu/pkg/config"
)

var (
	upgrader = &websocket.Upgrader{} // use default options, 各个业务互不影响.
)

func AsrHandler(ctx *gin.Context) {
	conn, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		http.Error(ctx.Writer, err.Error(), http.StatusBadRequest)
		log.Logger.Infof(" AsrHandler error:%v ", err)
		return
	}
	codecString := ctx.Query("codec")

	// codecString为编码类型，如g711，amrnb或amrwb，后台需要自己解码.
	encoder := config.EncoderConfig{Audio: config.AudioConfig{Codec: codecString, Channels: 1, Frame: 20, Frequency: 8000}, BUseUnixSocket: false}

	// 媒体层ip:LocalMediaIp从配置文件获取.
	mainHandler := asr.NewHandler(config.Config{Encoder: encoder, LocalMediaIp: AppConf.Http.Ip}, conn) // 媒体层用IT层的ip.
	mainHandler.Run("asrWorkServer")
}

// EmuRoomHandler WsRoomHandler ws升级入口.
// connect 时就处理，主要功能启动worker服务.
func EmuRoomHandler(c *gin.Context) {
	// 获取h264的连接参数.
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		http.Error(c.Writer, err.Error(), http.StatusBadRequest)
		return
	}

	// 处理逻辑.
	videoconfig := config.VideoConfig{Codec: "h264"}
	videoconfig.H264.Profile = "baseline"
	videoconfig.H264.Tune = "stillimage" // "zerolatency" // "stillimage"
	videoconfig.H264.Crf = 32
	videoconfig.H264.Preset = "fast"

	// 音频编码需要另外确定.
	encoder := config.EncoderConfig{Audio: config.AudioConfig{Codec: "g711", Channels: 1, Frame: 20, Frequency: 8000}, Video: videoconfig, BUseUnixSocket: false}

	// 媒体层ip, port?.
	// 分辨率先暂时写死.
	mainHandler := emu.NewHandler(config.Config{Encoder: encoder, Width: 540, Height: 960, LocalMediaIp: AppConf.Http.Ip}, conn) // 媒体层用IT层的ip.

	// taskId当做serverId启动.
	id := rand.New(rand.NewSource(time.Now().UnixNano())).Int()
	mainHandler.Run(strconv.Itoa(id))
}
